﻿using FileSystem.Impl;
using FileSystem.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FileSystem.impl.Commands
{
    class LinkCommand : ICommand, ICommandPrototype
    {
        private static LinkCommand zombie;
	
		private static void loadEmulator() {
            zombie = new LinkCommand(new HelpDescription() { Name = "cd", Description = "Link Command" });
			ICommandPrototypeRegistry r = AppResources.getInstance().getCommandRegistry();
			r.register("link", zombie);
		}

        private string linkName;
        private String nodeName;
		private IFSDirectory cwd;
      
		private bool executeSucceeded;
		private IResult lastResult;
        private IHelpDescription helpDescription;


        public IHelpDescription Description
        {
            get
            {
                return this.helpDescription;
            }
        }


        private LinkCommand(IHelpDescription helpDescription)
        {
            this.helpDescription = helpDescription;
			//for zombie
		}

        private LinkCommand(String linkName, String nodeName)
		{
			this.linkName = linkName;
            this.nodeName = nodeName;
			executeSucceeded = false;
		}
	
		public ICommand clone() {
			//Cannot clone touch without name of file as arg.
			return null;
		}
	
		public ICommand clone(String arg) {
            string linkName = StringUtil.firstToken(arg);
            string nodeName = StringUtil.remainder(arg);

            LinkCommand rc = new LinkCommand(linkName, nodeName);
			return rc;
		}

		public IResult execute() {
            this.cwd = AppResources.getInstance().getFileSystem().CurrentDirectory;
            IFSNode node = cwd.GetByName(this.nodeName);
	        
			lastResult = null;
			executeSucceeded = false;

            if (node != null)
            {
                INodeMetaDataVO metaData = AppResources.getInstance().getFileSystem().getMetaDataForEmptyNode(this.linkName);
                FSLink file = new FSLink(metaData, node);
                this.cwd.addNode(file);
                lastResult = new Result(file.getName()); 
            }
            else
            {
                lastResult = new Result(true, "Given node could not be found.");
            }

			return lastResult;
		}
	
		public void undo() {
            //if (!executeSucceeded) {
            //    //nothing to do, because execution failed...
            //    //we don't want to remove the node that might have been there of the same name.
            //    return;
            //}
            //AppResources.getInstance().getFileSystem().CurrentDirectory = cwd;
		}
	
		public IResult redo() {
			return execute();
		}
	
		public String describe(IPrintContext context) {
			return context.getFormattedString("link " + this.linkName + "(" + executeSucceeded + ").");
		}

    }
}
